package com.lzx.iteam;

import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import com.lzx.iteam.adapter.ConversationListAdapterEx;
import com.lzx.iteam.net.AsynHttpClient;
import com.lzx.iteam.util.PreferenceUtil;
import io.rong.imkit.RongContext;
import io.rong.imkit.RongIM;
import io.rong.imkit.fragment.ConversationListFragment;
import io.rong.imlib.RongIMClient;
import io.rong.imlib.model.Conversation;

import static android.content.ContentValues.TAG;


/**
 * Created with IntelliJ IDEA.
 * **********************************
 * User: zhangshuai
 * Date: 2016年 10月 20日
 * Time: 上午11:41
 *
 * @QQ : 1234567890
 * **********************************
 */
public class ChatFragment extends Fragment implements View.OnClickListener{

    /**
     * 会话列表的fragment
     */
    private String TAG = "ChatFragment";
    private Fragment mConversationListFragment = null;

    private View rootView;
    private PreferenceUtil mPreferenceUtil;

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mPreferenceUtil = PreferenceUtil.getInstance(getActivity());

    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {

        if (rootView == null){
            rootView = inflater.inflate(R.layout.chat_fragment_layout, container, false);

            String token = mPreferenceUtil.getString(AsynHttpClient.KEY_RONG_TOKEN, "");//loginToken
            Fragment conversationList = initConversationList();
            getChildFragmentManager()
                  .beginTransaction()
                  .add(R.id.chat_ll_layout, conversationList)
                  .addToBackStack(null)
                  .commitAllowingStateLoss();
//                  .commit();
//            reconnect(token);
            rootView.findViewById(R.id.rl_group_add).setOnClickListener(this);

        }

        // 缓存的rootView需要判断是否已经被加过parent，如果有parent需要从parent删除，要不然会发生这个rootview已经有parent的错误。
        ViewGroup parent = (ViewGroup) rootView.getParent();
        if (parent != null) {
            parent.removeView(rootView);
        }
        return rootView;
    }

    private void reconnect(String token) {

        RongIM.connect(token, new RongIMClient.ConnectCallback() {
            @Override
            public void onTokenIncorrect() {

                Log.e(TAG, "---onTokenIncorrect--");

                Log.d("ConnectionStatus", "fragment Status == 连接成功 ");
            }

            @Override
            public void onSuccess(String s) {
                Log.i(TAG, "---onSuccess--" + s);
                Fragment conversationList = initConversationList();
                getChildFragmentManager()
                      .beginTransaction()
                      .add(R.id.chat_ll_layout, conversationList)
                      .addToBackStack(null)
                      .commitAllowingStateLoss();

            }

            @Override
            public void onError(RongIMClient.ErrorCode e) {
                Log.e(TAG, "---onError--" + e);

            }
        });

    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.rl_group_add:
                Intent intent = new Intent(getActivity(), ChooseContactByTeamActivity.class);
                intent.setAction("create_chat_group");
                intent.putExtra("isSingle",false);
                startActivity(intent);
                break;
        }
    }

    private Fragment initConversationList() {
        if (mConversationListFragment == null) {
            ConversationListFragment listFragment = ConversationListFragment.getInstance();
            listFragment.setAdapter(new ConversationListAdapterEx(RongContext.getInstance()));
            Uri uri;
//            if (isDebug) {
                uri = Uri.parse("rong://" + getActivity().getApplicationInfo().packageName).buildUpon()
                        .appendPath("conversationlist")
                        .appendQueryParameter(Conversation.ConversationType.PRIVATE.getName(), "false") //设置私聊会话是否聚合显示
                        .appendQueryParameter(Conversation.ConversationType.GROUP.getName(), "false")//群组
                        .appendQueryParameter(Conversation.ConversationType.PUBLIC_SERVICE.getName(), "false")//公共服务号
                        .appendQueryParameter(Conversation.ConversationType.APP_PUBLIC_SERVICE.getName(), "false")//订阅号
                        .appendQueryParameter(Conversation.ConversationType.SYSTEM.getName(), "false")//系统
                        .appendQueryParameter(Conversation.ConversationType.DISCUSSION.getName(), "false")
                        .build();
            /*} else {
            uri = Uri.parse("rong://" + getActivity().getApplicationInfo().packageName).buildUpon()
                  .appendPath("conversationlist")
                  .appendQueryParameter(Conversation.ConversationType.PRIVATE.getName(), "false") //设置私聊会话是否聚合显示
                  .appendQueryParameter(Conversation.ConversationType.GROUP.getName(), "false")//群组
                  .appendQueryParameter(Conversation.ConversationType.PUBLIC_SERVICE.getName(), "false")//公共服务号
                  .appendQueryParameter(Conversation.ConversationType.APP_PUBLIC_SERVICE.getName(), "false")//订阅号
                  .appendQueryParameter(Conversation.ConversationType.SYSTEM.getName(), "true")//系统
                  .build();
            }*/
            listFragment.setUri(uri);
            return listFragment;
        } else {
            return mConversationListFragment;
        }
    }
}
